package com.pocketmenu.persistence;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.pocketmenu.business.Constants;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class CategoryDataSource {
	private int i=0;
	private CategoryDataSource h=this;
	// Database fields
		  private SQLiteDatabase database;
		  private SQLiteHelper dbHelper;
		  private String[] allColumns = 
			  { SQLiteHelper.COLUMN_ID,
				SQLiteHelper.COLUMN_CATEGORY_NAME,
				SQLiteHelper.COLUMN_CATEGORY_ID_RESTAURANT};

		  private SoapPrimitive resultado;
		  private boolean waitingForThread = true;
		  private boolean success = true;
		  
		  public CategoryDataSource(Context context) {
		    dbHelper = new SQLiteHelper(context);
		  }

		  public void open() throws SQLException {
		    database = dbHelper.getWritableDatabase();
		  }

		  public void close() {
		    dbHelper.close();
		  }

		  public Category create(String name, int idRestaurant) {
		    ContentValues values = new ContentValues();
		    values.put(SQLiteHelper.COLUMN_CATEGORY_NAME, name);
		    values.put(SQLiteHelper.COLUMN_CATEGORY_ID_RESTAURANT, idRestaurant);		    
		    
		    long insertId = database.insert(SQLiteHelper.TABLE_CATEGORY, null,
		        values);
		    
		    Cursor cursor = database.query(SQLiteHelper.TABLE_CATEGORY,
		        allColumns, SQLiteHelper.COLUMN_ID + " = " + insertId, null,
		        null, null, null);
		    cursor.moveToFirst();
		    Category newTemp = cursorToObject(cursor);
		    cursor.close();
		    return newTemp;
		  }

		  public void delete(Category toDelete) {
		    int id = toDelete.getId();
		    System.out.println("Category deleted with id: " + id);
		    database.delete(SQLiteHelper.TABLE_CATEGORY, SQLiteHelper.COLUMN_ID
		        + " = " + id, null);
		  }

		  public List<Category> getAll() {
		    List<Category> listTemp = new ArrayList<Category>();

		    Cursor cursor = database.query(SQLiteHelper.TABLE_CATEGORY,
		        allColumns, null, null, null, null, null);

		    cursor.moveToFirst();
		    while (!cursor.isAfterLast()) {
		      Category temp = cursorToObject(cursor);
		      listTemp.add(temp);
		      cursor.moveToNext();
		    }
		    // Make sure to close the cursor
		    cursor.close();
		    return listTemp;
		  }

		  public Category cursorToObject(Cursor cursor) {
		    Category temp = new Category();
		    temp.setId(cursor.getInt(0));
		    temp.setName(cursor.getString(1));
		    temp.setIdRestaurant(cursor.getInt(2));		    
		    return temp;
		  }
		  
		  public Cursor getAll(int idRestaurant) {
			  String whereClause = SQLiteHelper.COLUMN_CATEGORY_ID_RESTAURANT + "=" + idRestaurant;
			    Cursor cursor = database.query(SQLiteHelper.TABLE_CATEGORY,
			        allColumns, whereClause, null, null, null, null);

			    return cursor;
			  }		  		  
		  
		  public boolean loadFromWeb(){
			  Thread networkThread = new Thread() {
	      	    @Override
	      	    public void run() {
		      	      
		  	    	//request       	    
		      	    String metodo = "select";	
		      	    SoapObject request= new SoapObject(Constants.namespace, metodo);
		      	    request.addProperty("tabla", "Category");
		
		      	    //modelo sobre
		      	    SoapSerializationEnvelope sobre= new SoapSerializationEnvelope(SoapEnvelope.VER11);
		      	    sobre.dotNet = true;
		
		      	    sobre.setOutputSoapObject(request);
		
		      	    //transporte
		      	    HttpTransportSE transporte= new HttpTransportSE(Constants.url,10000);	          
		      	    transporte.debug = true;           
		
		      	    //llamada
		      	    try {
		      	    	transporte.call(Constants.namespace+metodo, sobre);
			   			
			   			//resultado
			   			resultado = (SoapPrimitive) sobre.getResponse();	   					   			
				   		success = true;
				   		
			   			} catch (Exception e) {
		   					Log.i("App.err " + getClass().getSimpleName(), e.getMessage());
			   				e.printStackTrace();
			   				success = false;
			   			}
		      	    waitingForThread = false;
	      	    }	      	      
	  	    };
	  	    networkThread.start();
	  	    
	  	    while(waitingForThread){	      	    	
	  	    }
	  	    
	  	    if(success)
	  	    	return loadDataToDatabase();
	  	    else
	  	    	return false;
		  }
		  
		  private boolean loadDataToDatabase()
		  {
			  try
			  {						
				String respuesta=resultado.toString();
				String[] restaurantesWeb = respuesta.split(";");
					
				database.execSQL("DROP TABLE IF EXISTS " + SQLiteHelper.TABLE_CATEGORY);
				database.execSQL(SQLiteHelper.TABLE_CREATE_CATEGORY);
				
				for(int i=0;i<restaurantesWeb.length;i++){
					String[] restauranteWebActual=restaurantesWeb[i].split("\\*");
					h.create(restauranteWebActual[1], Integer.parseInt(restauranteWebActual[2]));				
				}
				success = true;
				Log.i("App.log " + getClass().getSimpleName(), "Exito");
			  }
			  catch(Exception e)
			  {
				  Log.i("App.err " + getClass().getSimpleName(), e.getMessage());
				  e.printStackTrace();
				  success = false;
			  }
			  
			  return success;
		  }
}
